package cn.jia.hrm.service.impl;

import cn.jia.hrm.domain.LoginUser;
import cn.jia.hrm.encrypt.HttpUtil;
import cn.jia.hrm.exception.AssertGlobal;
import cn.jia.hrm.mapper.LoginUserMapper;
import cn.jia.hrm.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jia
 * @since 2021-09-11
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    private String URL_TOKEN = "http://localhost:4021/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";

    @Autowired
    private LoginUserMapper loginUserMapper ;

    @Override
    public Map<String, String> login(LoginUser loginUser) {
        //1.校验参数
        AssertGlobal.hasText(loginUser.getUsername(),"用户名不可为空");
        AssertGlobal.hasText(loginUser.getPassword(),"密码不可为空");

        LoginUser loginUserFromDB = loginUserMapper.seleByusername(loginUser.getUsername());
       // AssertGlobal.hasText(loginUserFromDB , "用户名不存在");

        //2.拼接获取Token的URL(password模式)
        String clientId = loginUserFromDB.getClientId();
        String clientSecret = loginUserFromDB.getClientSecret();

        //拼接完整的token的url
        String completeUrl = String.format(URL_TOKEN ,
                clientId , clientSecret , loginUser.getUsername() , loginUser.getPassword() );


        //3.发送HTTP请求，获取Token
        Map<String, String> resultMap = HttpUtil.sendPost(completeUrl);
        //转发失败是端口的原因
       /* "http://localhost:4021/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";*/

        //4.返回结果
        return resultMap;
    }
}
